package top.choviwu.garbage.sort.util;

import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil;
import com.baidu.aip.imageclassify.AipImageClassify;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import static top.choviwu.garbage.sort.constant.Constants.*;

@Data
@Component
@Slf4j
public class BaiduGsUtils {

    public final static Map<String, String> CACHED = MapBuilder.create(new ConcurrentHashMap<String, String>()).build();
    //设置APPID/AK/SK
    @Value("${baidu.appid}")
    private String appid;
    @Value("${baidu.apikey}")
    private String apikey;
    @Value("${baidu.secretkey}")
    private String secretkey;


    @Autowired
    AipImageClassify aipImageClassify;


    private volatile static BaiduGsUtils UTIL = null;

    private BaiduGsUtils() {
    }

    @Bean
    @ConditionalOnMissingBean
    public AipImageClassify aipImageClassify() {
        /**
        * @Description: 初始化一个AipImageClassify
        */
        AipImageClassify aipImageClassify = new AipImageClassify(CACHED.get(BAIDU_APPID),
                CACHED.get(BAIDU_APIKEP),
                CACHED.get(BAIDU_APPSECRET));
        /**
        * 可选：设置网络连接参数
        */
        aipImageClassify.setConnectionTimeoutInMillis(CONNECT_TIMEOUT_MILLIS_SECOND);
        aipImageClassify.setSocketTimeoutInMillis(SOCKET_TIMEOUT_MILLIS_SECOND);

        return aipImageClassify;
    }


    /**
     * AI 识别照片
     * @param image
     * @return
     */
    public JSONObject aiImage(String image) {
        HashMap<String, String> options = MapUtil.newHashMap();
        options.put(BAIDU_NUM, TEN);
        try {
            JSONObject res = aipImageClassify.advancedGeneral(image, options);
            log.info("AI image result >>>>>>>{}", res);
            return res;
        }catch (Exception e){
            return new JSONObject();
        }
    }
}